<template>
    <div>
        <Spin fix v-if="spinShow">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>excel生成中，请稍后</div>
        </Spin>
        <Form :label-width="100" ref="formInline" :model="formInline">
            <div v-if="switchFlag">
                <Row :gutter="16" class="query-form" >
                    <i-col span="8">
                      <FormItem label="二级集团：" prop="twoLevelOrgId">
                        <two-level-org org-code v-model="formInline.twoLevelOrgId" ></two-level-org>
                      </FormItem>
                    </i-col>
                    <i-col span="8">
                      <FormItem label="企业名称：">
                        <company-select v-model="formInline.screenOrgName"></company-select>
                      </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="检查岗位：">
                            <Input v-model="formInline.screenPositionName" placeholder="请填写检查岗位"/>
                        </FormItem>
                    </i-col>

                </Row>
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                      <FormItem label="检查人：">
                        <Input v-model="formInline.screenUserName" placeholder="请填写检查人"/>
                      </FormItem>
                    </i-col>
                    <i-col span="8">
                      <FormItem label="排查日期：">
                        <DatePicker v-model="formInline.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择排查日期（开始，结束）"></DatePicker>
                      </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="排查部门：">
                            <Input v-model="formInline.department" placeholder="请填写排查公司"/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" class="query-form2">
                    <i-col span="24">
                      <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                        <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                      </div>
                    </i-col>
                </Row>
            </div>
            <div v-else>
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                      <FormItem label="二级集团：" prop="twoLevelOrgId">
                        <two-level-org org-code v-model="formInline.twoLevelOrgId" ></two-level-org>
                      </FormItem>
                    </i-col>
                    <i-col span="8">
                      <FormItem label="企业名称：">
                        <company-select v-model="formInline.screenOrgName"></company-select>
                      </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-cloud-download" class="ivu-btn-add" @click="exportExcel">导出</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！" @on-sort-change="querySort"
               :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
        <Row type="flex" justify="end" >
            <i-col>
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>
        <Modal title="用户列表" v-model="visible" width="400">
            <Table  :loading="loading2" border :columns="columns2" no-data-text="没有查询到相关数据！" @on-sort-change="querySort"
                   :data="infos2" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
            <div slot="footer" >
                <Button @click="visible=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {Api} from '../../../api'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {formatDate} from '@/tools/index'

    export default {
        name: "apsgTaskTimeout",
        data(){
            return{
                spinShow: false,
                visible: false,
                loading: false,
                loading2: false,
                switchFlag: false,
                formInline: {
                    se_date: [

                    ]
                },
                tableHeight: '',
                columns: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        title: "状态",
                        width: 160,
                        align: "center",
                        fixed: 'left',
                        key: 'taskStatus',

                    },
                    {
                        minWidth: 220,
                        title: '任务名称',
                        key: 'taskName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '排查日期',
                        key: 'taskDate',
                        align: 'center',
                        sortable: 'custom',
                        render: (h, params) => {
                            return h('span', this.formatDate(new Date(params.row.taskDate),"yyyy-MM-dd"));
                        }
                    },
                    {
                        minWidth: 230,
                        title: '排查公司',
                        key: 'screenOrgName',
                        align: 'center'
                    },
                    {
                        minWidth: 230,
                        title: '排查部门',
                        key: 'createOrgId',
                        align: 'center',
                        render: (h, params) => {
                            return h('span', params.row.department != ''&& params.row.department? params.row.department: params.row.createOrgId )
                        }
                    },
                    {
                        minWidth: 130,
                        title: '排查岗位',
                        key: 'screenPositionName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '排查人',
                        key: 'screenUserName',
                        align: 'center',
                        render: (h, params) => {
                            if(params.row.screenUserName== undefined){
                                return h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            if(params.row.screenUserId== undefined || params.row.screenUserId== null|| params.row.screenUserId== "") {
                                                this.queryUserByPosition(params.row.screenPositionId);
                                            }else{
                                                this.queryUserByUserId(params.row.screenUserId);
                                            }
                                        }
                                    }
                                }, '详情')
                            }else{
                                return h('span', params.row.screenUserName);
                            }
                        }
                    },
                    {
                        minWidth: 130,
                        title: '排查周期',
                        key: 'taskType',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.taskType == '1') {
                                return h('span', '年度')
                            } else if (params.row.taskType == '2') {
                                return h('span', '每天')
                            } else if (params.row.taskType == '3') {
                                return h('span',  '工作日')
                            }  else if (params.row.taskType[0] == '5') {
                                return h('span',  '自定义')
                            } else if (params.row.taskType == '8') {
                                return h('span', '双周')
                            } else if (params.row.taskType == '6') {
                                return h('span',  '月度')
                            } else if (params.row.taskType == '7') {
                                return h('span',  '季度')
                            } else if (params.row.taskType == '4') {
                                return h('span',  '半年')
                            }
                        }
                    },

                ],
                infos: [],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                pageSizeArray: [10, 20, 50],
                userInfo: {},
                infos2: [],
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        minWidth: 220,
                        title: '用户名称',
                        key: 'userName',
                        align: 'center'
                    },
                ]
            }
        },
        mounted(){
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.userInfo = sessionStorage('userId').getObject('userId');
            this.formInline.se_date = [new Date(new Date().getFullYear()+'-01-01'), new Date()];
            // console.log(this.formInline);
            this.query();
        },
        methods: {
            query(){
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                    orgId: this.userInfo.companyName
                };
                if(this.formInline.se_date.length!=0){
                    if(this.formInline.se_date[0] != '') this.formInline.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    if(this.formInline.se_date[1] != '')  this.formInline.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.getTaskTimeoutDataList, {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            cancel(){
                this.formInline = { se_date: [] };
                this.query();
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if(this.switchFlag) {
                    this.tableHeight = this.tableHeight - 44;
                }else{
                    this.tableHeight = this.tableHeight + 44;
                }
            },
            exportExcel(){
                let data = {
                    orgId: this.userInfo.companyName
                };
                if(this.formInline.se_date.length!=0){
                    this.formInline.startDate = this.formInline.se_date[0];
                    this.formInline.endDate = this.formInline.se_date[1];
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.spinShow = true;
                this.$http.get(Api.getTaskTimeoutDataList + '/excel',{
                    params: data,
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "超时任务("+ formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                    this.spinShow = false;
                }, function(res){
                    this.$Message.error('生成失败');
                    this.spinShow = false;
                })
            },
            queryUserByPosition(positionId){
                this.visible = true;
                this.loading2 = true;
                this.$http.get(Api.queryUsersByPositionId + positionId ).then((res) => {
                    this.loading2 = false;
                    this.infos2 = res.data.data;
                });
            },
            queryUserByUserId(userId){
                this.visible = true;
                this.loading2 = true;
                this.$http.get(Api.getUserByIds,{params:{ids:userId}} ).then((res) => {
                    this.loading2 = false;
                    this.infos2 = res.data.data;
                });
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            querySort({column, key, order}){
              this.formInline.key = key;
              this.formInline.order = order;
              this.query();
            }
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>

